import {messages} from "share/common";
/**
 * Created by Allen on 2018/3/19.
 */
import React from 'react'
import { connect } from 'react-redux'
import {Form, DatePicker, Switch, Icon, Button, Select, Spin, Alert, Checkbox, message, Modal, Col, Row} from 'antd'
const FormItem = Form.Item;
const Option = Select.Option;
const confirm = Modal.confirm;

import Searcher from 'components/searcher'
import moment from 'moment'
import debounce from 'lodash.debounce'
import myAgencyService from 'containers/my-agency/my-agency.service'
import 'styles/my-agency/new-agent.scss'

class NewAgency extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      data: [],
      billOptions: {},    //代理单据选项
      chosenOptions: [],  //选中的代理单据选项
      chosenOptions1OIDs: [], //选中的报销单选项ID
      chosenOptions2OIDs: [], //选中的申请单选项ID
      chosenOptions3OIDs: [], //选中的借款单选项ID
      endDateVerify: {}, //结束日期校验
      record: {
        proxyUserDTO: {
          status: ''
        }
      },
      loading: false,
      disabled: true,
      enabled: true,
      fetching: '',
      isCheckAll: true, //是否已增量全选
      checkAll1: false,   //报销单全选
      checkAll2: false,   //申请单全选
      checkAll3: false,   //借款单全选
      showAlert: false,    //选中要离职的人员时slide上方的提示
      principalHelp: '', //被代理人校验内容
      startAgencyDate: moment().locale('zh-cn').utcOffset(8), //代理开始时间
      endAgencyDate: null, //代理结束时间
      ifFirst: true, //判断是否是第一次进入
      bill1OIDOptions: [],
      bill2OIDOptions: [],
      bill3OIDOptions: [],
      status: '',
      hideStatusItem: true, //隐藏状态开关
    };
    this.handleSearch = debounce(this.handleSearch, 250)
  }

  componentWillMount(){}

  componentWillReceiveProps(nextProps) {
    if (nextProps.params.record && !nextProps.params.editFlag){  //编辑
      this.initBills(nextProps.params.billOptions);
      nextProps.params.editFlag = true;
      this.props.form.resetFields();
      this.setState({
        data: [],
        isNew: nextProps.params.isNew,
        record: nextProps.params.record,
        status: nextProps.status,
        proxyOID: nextProps.params.record.proxyUserDTO.userOID
      },() => {
        const { record } = this.state;
        if (record.proxyUserDTO.status === 1002){
          this.setState({
            showAlert: true,
            principalHelp:  messages('my-agency.key41',{arg1: record.proxyUserDTO.fullName,arg2: moment(record.proxyUserDTO.leavingDate).format('YYYY-MM-DD')}/*员工 {arg1} 将于 {arg2}离职，离职后该代理关系将自动禁用*/)
            });
        }else if (record.proxyUserDTO.status === 1003){
          this.setState({
            showAlert: true,
            principalHelp:  messages('my-agency.key42',{arg1: record.proxyUserDTO.fullName,arg2: moment(record.proxyUserDTO.leavingDate).format('YYYY-MM-DD')}/*员工 {arg1} 已于 {arg2}离职*/)
          })
        }else {
          this.setState({showAlert: false,principalHelp: ''})
        }
        let chosenOptions1OIDs = [];
        let chosenOptions2OIDs = [];
        let chosenOptions3OIDs = [];
        let checkAll1, checkAll2, checkAll3;
        record.customFormDTOs.map((billItem) => {
          if (billItem.entityType === 1001) { //申请单
            chosenOptions2OIDs.push({formOID: billItem.formOID, formName: billItem.formName});
          }
          if (billItem.entityType === 1002) { //报销单
            chosenOptions1OIDs.push({formOID: billItem.formOID, formName: billItem.formName});
          }
          if (billItem.entityType === 3001) { //借款单
            chosenOptions3OIDs.push({formOID: billItem.formOID, formName: billItem.formName});
          }
        });
        checkAll1 = chosenOptions1OIDs.length === this.state.bill1OIDOptions.length;
        checkAll2 = chosenOptions2OIDs.length === this.state.bill2OIDOptions.length;
        checkAll3 = chosenOptions3OIDs.length === this.state.bill3OIDOptions.length;
        let isCheckAll = record.proxyFormScope === 1001;
        this.setState({ chosenOptions1OIDs, chosenOptions2OIDs, chosenOptions3OIDs, checkAll1, checkAll2, checkAll3, isCheckAll });
      });

    } else if (nextProps.params.isNew && !nextProps.params.hasInit){                      //新建
      this.initBills(nextProps.params.billOptions);
      nextProps.params.hasInit = true;
      this.setState({
        data: [],
        record: null,
        isNew: nextProps.params.isNew,
        status: nextProps.status,
        isCheckAll: true,
        //非增量的默认不全选
        checkAll1: false,
        checkAll2: false,
        checkAll3: false
      },() => {
         if (this.state.ifFirst){
           this.setState({ifFirst: true, showAlert: false})
         }
         this.props.form.resetFields()
      });
    }
  }

  //billOptions 包含所有单据类型
  initBills = (billOptions) => {
    let resultOptions = {};
    let bill1OIDOptions = [];
    let bill2OIDOptions = [];
    let bill3OIDOptions = [];
    resultOptions = JSON.parse(JSON.stringify(billOptions));
    //报销单
    resultOptions.expenseBills && resultOptions.expenseBills.map(item => {
      bill1OIDOptions.push({formOID: item.formOID, formName: item.formName});
    });
    //申请单
    resultOptions.requestBills && resultOptions.requestBills.map(item => {
      bill2OIDOptions.push({formOID: item.formOID, formName: item.formName});
    });
    //借款单
    resultOptions.loanBills && resultOptions.loanBills.map(item => {
      bill3OIDOptions.push({formOID: item.formOID, formName: item.formName});
    });
    this.setState({ bill1OIDOptions, bill2OIDOptions, bill3OIDOptions, billOptions: resultOptions });
  };

  //代理人发生改变
  handleChange = () => {
    const { status, bill1OIDOptions, bill2OIDOptions, bill3OIDOptions } = this.state;
    this.setState({
      chosenOptions1OIDs: bill1OIDOptions,
      chosenOptions2OIDs: bill2OIDOptions,
      chosenOptions3OIDs: bill3OIDOptions
    },() => {
      this.props.form.setFieldsValue({chosenOptions1OIDs: []});
      this.props.form.setFieldsValue({chosenOptions2OIDs: []});
      this.props.form.setFieldsValue({chosenOptions3OIDs: []});
      this.setState({checkAll1: false, checkAll2: false, checkAll3: false});
    });
  };

  //查询代理人下拉列表
  handleSearch = (value) => {
    const { status, record } = this.state;
    value && this.setState({
      principalHelp: '',
      showAlert: false,
      fetching: true
    });
    let operationCode = status === 'AGENT' ? 2 : 1;
    let params = {
      operationCode,
      ruleOID: record && record.ruleOID ? record.ruleOID : ''
    };
    value && myAgencyService.getPersonByValue(value, params).then(resp => {
      let data = resp.data.rows;
      data.map(item => {
        item.text = `${item.fullName} - ${item.employeeID}`
      });
      this.setState({ data, fetching: false })
    })
  };

  //选中代理人后查询该代理人状态（是否已存在、是否将离职）
  handleSelect = (e, opt) => {
    let principalInfo = JSON.parse(JSON.stringify(opt.props['data-user']));
    this.setState({proxyOID: principalInfo.userOID, showAlert: false});
    if (principalInfo.status === 1002){
      this.setState({
        showAlert: true,
        principalHelp: messages('my-agency.key41',{arg1: principalInfo.fullName,arg2: moment(principalInfo.leavingDate).format('YYYY-MM-DD')}/*员工 {arg1} 将于 {arg2}离职，离职后该代理关系将自动禁用*/)
      });
    } else if (principalInfo.status === 1003){
      this.setState({
        enabled: false,
        showAlert: true,
        principalHelp: messages('my-agency.key42',{arg1: principalInfo.fullName,arg2: moment(principalInfo.leavingDate).format('YYYY-MM-DD')}/*员工 {arg1} 已于 {arg2}离职*/)
      })
    } else {
      this.setState({enabled: true,showAlert: false})
    }
  };

  //开始代理日期 <= 结束代理日期 且 开始代理日期 >= 今天
  disabledStartDate = (startAgencyDate) => {
    let endAgencyDate = moment(moment(this.state.endAgencyDate).format('YYYY-MM-DD 23:59:59'));
    if (!startAgencyDate || !endAgencyDate) {
      return false
    }
    return startAgencyDate.valueOf() < new Date(new Date().format('yyyy-MM-dd 00:00:00')).valueOf()
      || startAgencyDate.valueOf() > endAgencyDate.valueOf();
  };

  //结束代理日期 >= 开始代理日期 且 结束代理日期 >= 今天
  disabledEndDate = (endAgencyDate) => {
    const startAgencyDate = moment(moment(this.state.startAgencyDate).format('YYYY-MM-DD 00:00:00'));
    if (!endAgencyDate || !startAgencyDate) {
      return false
    }
    if (startAgencyDate.valueOf() < new Date().valueOf()) {
      return endAgencyDate.valueOf() < new Date(new Date().format('yyyy-MM-dd 00:00:00')).valueOf()
    }
    return endAgencyDate.valueOf() < startAgencyDate.valueOf()
  };

  //保存新建我的代理人
  handleSave = (e) => {
    const { billOptions, status, isCheckAll } = this.state;

    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        let chosenOptions = [];
        let chosenOptions1OIDs = values.chosenOptions1OIDs;
        let chosenOptions2OIDs = values.chosenOptions2OIDs;
        let chosenOptions3OIDs = values.chosenOptions3OIDs;
        if (chosenOptions1OIDs){
          chosenOptions1OIDs.map(value => {
            billOptions.expenseBills.map(item => {
              item.formOID === value.formOID  && chosenOptions.push(item)
            })
          });
        }
        if (chosenOptions2OIDs){
          chosenOptions2OIDs.map(value => {
            billOptions.requestBills.map(item => {
              item.formOID === value.formOID && chosenOptions.push(item)
            })
          });
        }
        if (chosenOptions3OIDs){
          chosenOptions3OIDs.map(value => {
            billOptions.loanBills.map(item => {
              item.formOID === value.formOID && chosenOptions.push(item)
            })
          });
        }
        if (chosenOptions.length === 0 && !isCheckAll){
          message.error(messages('my-agency.key29'/*请选择代理单据*/));
          return false;
        }
        if (values.endDate && values.endDate.valueOf() < new Date(new Date().format('yyyy-MM-dd 00:00:00')).valueOf()){
          this.setState({
            endDateVerify: {
              status: 'error',
              help: messages('my-agency.key30'/*结束日期不能早于今天*/)
            }
          });
          return false;
        }else {
          this.setState({endDateVerify: {}});
        }
        let params = {
          enabled: values.enabled,
          startDate: values.startDate,
          endDate: values.endDate ? values.endDate : null,
          proxyTimeRange: values.endDate ? 102 : 101,
          proxyOperationType: status === 'AGENT' ? 2 : 1,
          principalOID: this.state.record? this.state.record.principalOID :this.props.user.userOID,  //当前用户的OID
          proxyOID: this.state.proxyOID,        //选中的代理人的OID
          customFormDTOs: isCheckAll ? [] : chosenOptions,
          proxyFormScope: isCheckAll ? 1001 : 1002,
          ruleOID: this.state.record ? this.state.record.ruleOID : null
        };
        this.setState({loading: true});
        if (params.enabled === false){
          const that = this;
          confirm({
            title: messages('my-agency.key31'/*代理关系未启用*/),
            content: <div><span style={{color: 'red'}}>{messages('my-agency.key32'/*未启用的代理将不会生效,*/)}</span>{messages('my-agency.key33'/*是否继续保存？*/)}</div>,
            okText: messages('common.save'),
            onOk(){
              myAgencyService.saveAgent(params).then(resp => {
                if (resp.data === true){
                  message.success(messages('my-agency.key34'/*保存成功*/));
                  that.setState({showAlert: false,loading: false,ifFirst: true,data: []});
                  that.props.form.resetFields();
                  that.props.close(true);
                }
              }).catch(error => {
                message.error(messages('common.save.filed'));
                that.setState({loading: false,data: []});
                that.props.close(true);
              })
            },
            onCancel: () => {
              this.props.form.resetFields();
              this.setState({loading: false, data: []})
            }
          })
        }else {
          myAgencyService.saveAgent(params).then(resp => {
            if (resp.data === true){
              message.success(messages('my-agency.key34'/*保存成功*/));
              this.setState({showAlert: false, loading: false, checkAll1: true, checkAll2: true, checkAll3: true, ifFirst: true, data: []});
              this.props.form.resetFields();
              this.props.close(true);
            }
          }).catch(error => {
            message.error(messages('common.save.filed'));
            this.setState({loading: false,data: []});
          })
        }
      }
    });
  };

  onCancel =() =>{
    this.setState({showAlert: false,ifFirst: true});
    this.props.form.resetFields();
    this.props.close()
  };

  //修改选择的单据
  handleBillsChange = (type, values) => {
    if (type === 'request' && values.length === this.state.billOptions.requestBills.length) { //申请单
      this.setState({ checkAll2: true });
    } else if (type === 'expense' && values.length === this.state.billOptions.expenseBills.length) { //报销单
      this.setState({ checkAll1: true });
    } else if (type === 'loan' && values.length === this.state.billOptions.loanBills.length) { //借款单
      this.setState({ checkAll3: true });
    }
  };

  render(){

    const { getFieldDecorator } = this.props.form;
    const { record, status, fetching, showAlert, data, principalHelp, isNew, chosenOptions1OIDs, chosenOptions2OIDs, chosenOptions3OIDs,
      bill1OIDOptions, bill2OIDOptions, bill3OIDOptions, endDateVerify, loading, checkAll1, checkAll2, checkAll3, isCheckAll, hideStatusItem } = this.state;
    const formItemLayout = {
      labelCol: {span: 6},
      wrapperCol: {span: 10, offset: 1}
    };

    return (
      <div className="new-agent">
        {showAlert && (
          <Alert message={messages('common.help')}
                 description={principalHelp}
                 type="warning"
                 showIcon/>
        )}
        <Form onSubmit={(e) => {this.handleSubmit(e, key)}}>
          {/*task#41098 我的代理 - 新建代理 - 状态按钮前端隐藏*/}
          {!hideStatusItem && (
            <FormItem {...formItemLayout} label={messages('common.column.status')}> {/*状态*/}
            {getFieldDecorator('enabled',{
              initialValue: record ? record.enabled : true,
              valuePropName: 'checked'
            })(
              <Switch checkedChildren={<Icon type="check"/>}
                      disabled
                      unCheckedChildren={<Icon type="cross"/>} onChange={this.changeStatus}/>
            )}
          </FormItem>)}
          <div id="selectAgent" style={{position: 'relative'}}>
            <FormItem {...formItemLayout}
                      label={messages('my-agency.key23'/*代理人*/)}> {/*代理人*/}
              {getFieldDecorator('record.principalUserDTO.fullName',{
                rules: [{
                  required: true,
                  message: messages('my-agency.key35'/*请选择代理人*/)
                }],
                initialValue: record ? record.proxyUserDTO.fullName : undefined //undefined才有placeholder展示
              })(
                <Select disabled={status === 'AGENCY'}
                        showSearch
                        placeholder={messages('my-agency.key50')/*搜索姓名或工号*/}
                        allowClear
                        filterOption={false}
                        getPopupContainer={() => document.getElementById('selectAgent')}
                        notFoundContent={fetching === true ? <Spin size="small" /> : fetching === false ? <div>
                          <div>{messages('my-agency.key36'/*无搜索结果，原因可能为以下情况：*/)}</div>
                          <div>1.{messages('my-agency.key37'/*该员工不存在：*/)}</div>
                          <div>2.{messages('my-agency.key38'/*该员工已离职*/)}</div>
                          <div>3.{messages('my-agency.key39'/*已为该员工创建过代理关系*/)}</div>
                        </div> : <div/>}
                        onChange={this.handleChange}
                        onSearch={this.handleSearch}
                        onSelect={(e, opt) => this.handleSelect(e, opt)}>
                  {data.map(d => <Option key={d.userOID} value={d.text} data-user={d}>{d.text}</Option>)}
                </Select>
              )}
            </FormItem>
          </div>
          <div id="selectStartDate" style={{position: 'relative'}}>
            <FormItem {...formItemLayout} label={messages('my-agency.key25'/*开始日期*/)}> {/*开始日期*/}
              {getFieldDecorator('startDate',{
                rules: [{
                  required: true,
                  message: messages('my-agency.key40'/*请选择开始日期*/)
                }],
                initialValue: record ? moment(record.startDate) : moment(new Date())
              })(
                <DatePicker format="YYYY-MM-DD"
                            placeholder={messages('my-agency.key40'/*请选择开始日期*/)}
                            disabled={status === 'AGENCY'}
                            disabledDate={this.disabledStartDate}
                            getCalendarContainer={() => document.getElementById('selectStartDate')}
                            onChange={date => this.setState({startAgencyDate: date})}/>
              )}
            </FormItem>
          </div>
          <div id="selectEndDate" style={{position: 'relative'}}>
            <FormItem {...formItemLayout}
                      validateStatus={endDateVerify.status || ''}
                      help={endDateVerify.help || ''}
                      label={messages('my-agency.key26'/*结束日期*/)}> {/*结束日期*/}
              {getFieldDecorator('endDate',{
                initialValue: record && record.endDate ? moment(record.endDate) : null
              })(
                <DatePicker format="YYYY-MM-DD"
                            placeholder={messages('my-agency.key12'/*无限制*/)}
                            disabled={status === 'AGENCY'}
                            disabledDate={this.disabledEndDate}
                            getCalendarContainer={() => document.getElementById('selectEndDate')}
                            onChange={date => this.setState({endAgencyDate: date})}/>
              )}
            </FormItem>
          </div>
          <Row className="check-all-block">
            <Col span={6} style={{textAlign: 'right'}}>{messages('my-agency.key6'/*代理单据*/)}：</Col>
            <Col offset={1} span={10} >
              <Checkbox checked={isCheckAll}
                        onClick={(e) => this.setState({isCheckAll: e.target.checked})}>
                {messages('common.all')}
              </Checkbox>
            </Col>
          </Row>
          <div className="document-form-container">
            <FormItem {...formItemLayout}
                      label={messages('my-agency.key27'/*报销单*/)}>
                <div>
                  {getFieldDecorator('chosenOptions1OIDs',{
                    initialValue: isNew ? (checkAll1 ? bill1OIDOptions : []) : chosenOptions1OIDs
                  })(
                    <Searcher type={status === 'AGENT' ? "proxy_form" : "proxy_form_apply"}
                              listExtraParams={{customFormType: 1002}}
                              labelKey="formName"
                              descriptionKey="companyName"
                              disabled={isCheckAll}
                              placeholder=""
                              showNumber
                              isShowSelectAll
                              isAll={isCheckAll}
                              showClear={false}
                              onChange={values => this.handleBillsChange('expense', values)}
                    />
                  )}
                </div>
            </FormItem>
            <FormItem {...formItemLayout}
                      label={messages('my-agency.key28'/*申请单*/)}>

                <div>
                  {getFieldDecorator('chosenOptions2OIDs',{
                    initialValue: isNew ? (checkAll2 ? bill2OIDOptions : []) : chosenOptions2OIDs
                  })(
                    <Searcher type={status === 'AGENT' ? "proxy_form" : "proxy_form_apply"}
                              listExtraParams={{customFormType: 1001}}
                              labelKey="formName"
                              descriptionKey="companyName"
                              disabled={isCheckAll}
                              placeholder=""
                              showNumber
                              isShowSelectAll
                              isAll={isCheckAll}
                              showClear={false}
                              onChange={values => this.handleBillsChange('request', values)}
                    />
                  )}
                </div>
            </FormItem>
            <FormItem {...formItemLayout} label={messages('my-agency.key49')/*借款单*/}>
              <div>
                {getFieldDecorator('chosenOptions3OIDs',{
                  initialValue: isNew ? (checkAll3 ? bill3OIDOptions : []) : chosenOptions3OIDs
                })(
                  <Searcher type={status === 'AGENT' ? "proxy_form" : "proxy_form_apply"}
                            listExtraParams={{customFormType: 3001}}
                            labelKey="formName"
                            descriptionKey="companyName"
                            disabled={isCheckAll}
                            placeholder=""
                            showNumber
                            isShowSelectAll
                            isAll={isCheckAll}
                            showClear={false}
                            onChange={values => this.handleBillsChange('loan', values)}
                  />
                )}
              </div>
            </FormItem>
          </div>
          <div className="slide-footer">
            <Button type="primary" htmlType="submit" onClick={this.handleSave} loading={loading}>
              {messages('common.save')}</Button>
            <Button onClick={this.onCancel}>{messages('common.back')}</Button>
          </div>
        </Form>
      </div>
    )

  }

}

function mapStateToProps(state) {
  return {
    user: state.login.user
  }
}

const WrappedNewAgency = Form.create()(NewAgency);

export default connect(mapStateToProps)(WrappedNewAgency)

